package com.meishij.fragment;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.PtrHandler;
import com.chanven.lib.cptr.PtrUIHandler;
import com.chanven.lib.cptr.indicator.PtrIndicator;
import com.chanven.lib.cptr.loadmore.DefaultLoadMoreViewFooter;
import com.chanven.lib.cptr.loadmore.ILoadMoreViewFactory;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.meishij.R;
import com.meishij.activity.ShiHua_Loc_City_Activity;
import com.meishij.adapter.ShiHua_New_Main_VP_Adpater;
import com.meishij.customerview.GuoLoadDialog;
import com.meishij.entry.ShihuaEntry;
import com.meishij.server.ShiHuaServer;

import org.w3c.dom.Text;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static android.util.Log.e;

/**
 * A simple {@link Fragment} subclass.
 */
public class ShiHFragment extends Fragment implements Callback<ShihuaEntry>, View.OnClickListener {


    private RecyclerView recyclerView;
    private ShiHuaServer shiHuaServer;
    private List<Object> list;
    private FloatingActionButton back_top_Button;
    private FloatingActionButton user_track_Button;
    private ImageView tv_top_head;
    private PopupWindow popupWindow;

    private TextView tv_fsh;
    private PtrClassicFrameLayout ptr_Layout;
    private View pullToHeadView;
    private ImageView iv_ptr;
    private TextView tv_ptr_notify;
    private TextView tv_ptr_time;
    private AnimationDrawable animationDrawable;
    private int hottopic_page = 2;

    private boolean isFirst = true;
    private boolean canPullToRefresh = false;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    ptr_Layout.refreshComplete();
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private Call<ShihuaEntry> shihuaEntry;
    private ShiHua_New_Main_VP_Adpater shiHua_new_main_vp_adpater;
    private TextView tv_top_loc;


    private View backView;
    private View inflate;
    private boolean addShiHuaTopicData;
    private GuoLoadDialog loadingDialogFirst;

    public ShiHFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (backView != null) {
            return backView;
        }
        inflate = inflater.inflate(R.layout.fragment_shih, container, false);
        return inflate;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (inflate != null) {
            backView = inflate;
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

        ptr_Layout = ((PtrClassicFrameLayout) view.findViewById(R.id.ptr_shihua_pull_to_refresh));
        setPtrHeaderLayout();

        recyclerView = (RecyclerView) view.findViewById(R.id.shihua_recylerview);
        back_top_Button = ((FloatingActionButton) view.findViewById(R.id.floatbutton_shihua_back_top_icon));
        user_track_Button = ((FloatingActionButton) view.findViewById(R.id.floatbutton_shihua_uesr_track));
        setBehaviorAndClick();

        loadingDialogFirst = new GuoLoadDialog(getContext(), R.style.MyDialog);
        loadingDialogFirst.setCanceledOnTouchOutside(false);


        tv_top_head = ((ImageView) view.findViewById(R.id.iv_shihua_top_head));
        tv_top_head.setOnClickListener(this);
        tv_top_loc = ((TextView) view.findViewById(R.id.iv_shihua_top_loc));
        tv_top_loc.setOnClickListener(this);

        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 1);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int postion) {
                return 1;
            }
        });
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // 向上滑动 :dy > 0
                // 向下滑动 :dy < 0
                if (dy > 0) {
                    back_top_Button.setVisibility(View.INVISIBLE);
                    user_track_Button.setVisibility(View.INVISIBLE);
                    if (recyclerView.canScrollVertically(1) == false) {
                        //Toast.makeText(getContext(), "已经到达底部,正在加载数据", Toast.LENGTH_SHORT).show();
                        addShiHuaTopicData = true;
                        loadingDialogFirst.show();
                        hottopic_page++;
                        Retrofit build = new Retrofit.Builder().baseUrl("http://api.meishi.cc/")
                                .addConverterFactory(GsonConverterFactory.create())
                                .build();
                        shiHuaServer = build.create(ShiHuaServer.class);
                        shihuaEntry = shiHuaServer.getHotTopicEntry(hottopic_page);
                        //异步调用
                        shihuaEntry.enqueue(ShiHFragment.this);
                    }
                } else {
                    back_top_Button.setVisibility(View.VISIBLE);
                    user_track_Button.setVisibility(View.VISIBLE);
                }
            }
        });
        if (shiHua_new_main_vp_adpater != null && list != null) {
            shiHua_new_main_vp_adpater = new ShiHua_New_Main_VP_Adpater(getContext(), list, new int[]{
                    R.layout.item_shihua_banner, R.layout.item_shihua_column_title,
                    R.layout.item_shihua_new_hot, R.layout.item_shihua_hotpic
            });
            recyclerView.setAdapter(shiHua_new_main_vp_adpater);
            isFirst = false;
        } else {
            Retrofit build = new Retrofit.Builder().baseUrl("http://api.meishi.cc/")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            shiHuaServer = build.create(ShiHuaServer.class);
            shihuaEntry = shiHuaServer.getShihuaEntry("time");
            //异步调用
            shihuaEntry.enqueue(this);
        }
    }

    private void setBehaviorAndClick() {
        back_top_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "顶部", Toast.LENGTH_SHORT).show();
            }
        });
        user_track_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(), "足迹", Toast.LENGTH_SHORT).show();
            }
        });
    }

  /*  private void setPtrFooterLayout() {
        ptr_Layout.setFooterView(new ILoadMoreViewFactory() {
            @Override
            public ILoadMoreView madeLoadMoreView() {
                return new ILoadMoreView() {

                    private View footview;
                    @Override
                    public void init(FootViewAdder footViewHolder, View.OnClickListener onClickLoadMoreListener) {

                        footview=footViewHolder.addFootView(R.layout.item_shihua_anim_ptr);
                        showNormal();
                    }

                    @Override
                    public void showNormal() {
                        footview.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void showNomore() {

                    }

                    @Override
                    public void showLoading() {

                    }

                    @Override
                    public void showFail(Exception e) {

                    }

                    @Override
                    public void setFooterVisibility(boolean isVisible) {
                        footview.setVisibility(isVisible ? View.VISIBLE : View.GONE);
                    }
                };

            }
        });
        ptr_Layout.setLoadMoreEnable(true);
    }*/


    private void setPtrHeaderLayout() {
        pullToHeadView = LayoutInflater.from(getContext()).inflate(R.layout.item_shihua_anim_ptr, null);
        iv_ptr = ((ImageView) pullToHeadView.findViewById(R.id.iv_shihua_top_anim));
        tv_ptr_notify = ((TextView) pullToHeadView.findViewById(R.id.tv_shihua_top_notify));
        tv_ptr_time = ((TextView) pullToHeadView.findViewById(R.id.tv_shihua_top_time));
        ptr_Layout.setHeaderView(pullToHeadView);
        //设置阻尼的效果
        ptr_Layout.setResistance(2.0f);
        ptr_Layout.setRatioOfHeaderHeightToRefresh(1.2f);
        //距离多少的时候就可以关闭
        ptr_Layout.setDurationToClose(200);
        ptr_Layout.setDurationToCloseHeader(1000);
        ptr_Layout.addPtrUIHandler(new PtrUIHandler() {
            @Override
            public void onUIReset(PtrFrameLayout frame) {
                if (animationDrawable != null) {
                    animationDrawable.stop();
                }
                tv_ptr_notify.setText("下拉刷新");
            }

            @Override
            public void onUIRefreshPrepare(PtrFrameLayout frame) {
                tv_ptr_notify.setText("下拉刷新");
            }

            @Override
            public void onUIRefreshBegin(PtrFrameLayout frame) {
                animationDrawable = (AnimationDrawable) iv_ptr.getDrawable();
                //帧动画开始
                animationDrawable.start();
                tv_ptr_notify.setText("正在努力加载数据");
            }

            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {
                if (animationDrawable != null) {
                    animationDrawable.stop();
                    tv_ptr_notify.setText("刷新成功");
                    tv_ptr_time.setText("上次更新时间:" + new SimpleDateFormat("MM-dd HH:mm:ss").format(new Date()));
                }
                iv_ptr.setImageResource(R.drawable.anim_shihua_pull_to_refresh);
            }

            @Override
            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                //ptrFrameLayout的下拉距离
                int offsetToRefresh = frame.getOffsetToRefresh();

                //当前滑动到的Y位置
                int currentPosY = ptrIndicator.getCurrentPosY();
                //上一次滑动到的Y位置
                int lastPosY = ptrIndicator.getLastPosY();
                //Log.e("Test", "onUIPositionChange"+offsetToRefresh+"  "+currentPosY+"  "+lastPosY);
                //向上滑或者下滑的距离 不到offsetToRefresh
                if (currentPosY < offsetToRefresh && lastPosY >= offsetToRefresh) {
                    if (isUnderTouch && status == PtrFrameLayout.PTR_STATUS_PREPARE) {
                        tv_ptr_notify.setText("下拉刷新");
                    }
                }//到达一定下拉滑动距离
                else if (currentPosY > offsetToRefresh && lastPosY <= offsetToRefresh) {
                    if (isUnderTouch && status == PtrFrameLayout.PTR_STATUS_PREPARE) {
                        tv_ptr_notify.setText("松开刷新");
                    }
                }
            }
        });

        ptr_Layout.setPtrHandler(new PtrHandler() {
            //判断ptr的是否可以进行下载加载
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if (canPullToRefresh) {
                    Retrofit build = new Retrofit.Builder().baseUrl("http://api.meishi.cc/")
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();
                    shiHuaServer = build.create(ShiHuaServer.class);
                    shihuaEntry = shiHuaServer.getShihuaEntry("time");
                    //异步调用
                    shihuaEntry.enqueue(ShiHFragment.this);
                    canPullToRefresh = false;
                    return;
                } else {
                    ptr_Layout.refreshComplete();
                }
            }
        });
    }


    @Override
    public void onResponse(Call<ShihuaEntry> call, Response<ShihuaEntry> response) {
        ShihuaEntry body = response.body();
        if (addShiHuaTopicData) {
            shiHua_new_main_vp_adpater.addHotTopicAll(body.getHot_topic());
            loadingDialogFirst.dismiss();
        } else {
            if (isFirst) {
                list = new ArrayList();
                list.add(0, body.getActivities2());
                list.add(1, body.getColumn());
                list.add(2, "最新最热");
                list.add(3, body.getHot_topic());
                shiHua_new_main_vp_adpater = new ShiHua_New_Main_VP_Adpater(getContext(), list, new int[]{
                        R.layout.item_shihua_banner, R.layout.item_shihua_column_title,
                        R.layout.item_shihua_new_hot, R.layout.item_shihua_hotpic
                });
                recyclerView.setAdapter(shiHua_new_main_vp_adpater);
            } else {
                shiHua_new_main_vp_adpater.remove(3);
                shiHua_new_main_vp_adpater.addNewData(3, body.getHot_topic());
                ptr_Layout.refreshComplete();
            }
        }
        isFirst = false;
        canPullToRefresh = true;
        addShiHuaTopicData = false;
    }

    @Override
    public void onFailure(Call<ShihuaEntry> call, Throwable t) {
        Toast.makeText(getContext(), "吃的太撑了 稍后再试试吧", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_shihua_top_head:
                if (popupWindow == null) {
                    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    View popView = inflater.inflate(R.layout.item_shihua_top_pop, null);
                    popupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
                    //点back键和其他地方使其消失,设置了这个才能触发OnDismisslistener
                    popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    tv_fsh = ((TextView) popView.findViewById(R.id.tv_shihua_top_fsh));
                    tv_fsh.setOnClickListener(this);
                }
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    //设置显示位置
                    popupWindow.showAsDropDown(v, 0, 0);
                }
                break;
            case R.id.tv_shihua_top_fsh:
                Toast.makeText(getContext(), "发食话", Toast.LENGTH_SHORT).show();
                break;
            case R.id.iv_shihua_top_loc:
                Intent intent = new Intent(getContext(), ShiHua_Loc_City_Activity.class);
                startActivity(intent);
                break;
        }
    }
}
